package com.example.wssapp.adapter;

import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.wssapp.R;

/**
 * 自定义适配器
 * 
 * @author sean
 * 
 */
public class CustomAdapter extends BaseAdapter {

	private Context ctx;
	private List<Item> items;

	public CustomAdapter(Context ctx, List<Item> items) {
		super();
		this.ctx = ctx;
		this.items = items;
	}

	@Override
	public int getCount() {
		return items == null ? 0 : items.size();
	}

	@Override
	public Object getItem(int position) {
		return null == items ? null : items.get(position);
	}

	@Override
	public long getItemId(int position) {

		return null == items ? 0l : items.get(position).hashCode();
	}

	@SuppressLint("InflateParams")
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		TextHolder th = null;
		if (null == v) {
			LayoutInflater lInflater = (LayoutInflater) ctx
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = lInflater.inflate(R.layout.item_layout, null);

			th = new TextHolder();
			// findViewById 是一个昂贵操作，在加载大量数据时，会造成列表不流畅。
			// 使用th保存引用，重复使用
			th.nameView = (TextView) v.findViewById(R.id.nameView);
			th.descrView = (TextView) v.findViewById(R.id.descrView);

			v.setTag(th);
		} else {
			th = (TextHolder) v.getTag();
		}

		Item item = items.get(position);
		th.nameView.setText(item.getName());
		th.descrView.setText(item.getDescr());

		return v;
	}

	// 应用View Holder模式
	static class TextHolder {
		private TextView nameView;
		private TextView descrView;
	}

}
